<template>
  <!-- 经典方案集锦 -->
  <div>
    <searchData :searchData="searchArr" @search="search" :empty="true" :emptyField="'partId'"></searchData>
    <a-card>
      <!-- 表格 -->
      <list-table
        ref="table"
        :columns="columns"
        :startIndex="0"
        :request="loadData"
        :exportConfig="{
          use: true,
          select: $route.meta.title,
          all: $route.meta.title,
          customColumns: columns
        }"
        :statisticsConfig="{ use: true, statistics, temp }"
      >
        <!-- 新增 -->
        <a-button
          v-btnPermission="'tm_031_add_01'"
          slot="prefix"
          class="mb12"
          icon="plus"
          type="primary"
          @click="handleManage(2)"
          >新增</a-button>
          <!-- 下载附件 -->
        <template slot="suffix" slot-scope="scoped">
          <a-button
          v-btnPermission="'tm_031_bat_07'"
            :loading="downLoading"
            class="mb12"
            icon="cloud-download"
            :disabled="scoped.selectedRowKeys && scoped.selectedRowKeys.length === 0"
            type="primary"
            @click="downZipFc(scoped.selectedRowKeys)" >批量下载附件</a-button
          >
        </template>
        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
        <span slot="nameStr" slot-scope="text, record">
          <a-tooltip placement="topLeft" :title="record.classicsTypeName">
            <span v-if="record.classicsTypeName=='局优秀'"> <a-tag color="pink"> 局优秀 </a-tag>{{ record.planName }}</span>
            <span v-else> <a-tag color="orange"> 公司优秀 </a-tag>{{ record.planName }}</span>
          </a-tooltip>
        </span>
        <span slot="versionNumber" slot-scope="text,record" style="cursor: pointer;color:#108DE9" @click="versionList(record)">
           {{getVersionNumber(text)}}
        </span>
        <span slot="operation" slot-scope="text, record">
          <MoreButton>
            <!-- <MoreButton> -->
            <a v-btnPermission="'tm_031_loo_04'" @click="handleManage(0, record)">查看</a>
            <!-- 编辑 -->
            <template v-if="record.auditStatus == 'DRAFT' || record.auditStatus == 'REJECTED'">
              <a  @click="handleManage(1, record)"
                v-btnPermission="'tm_031_edi_02'"
                >编辑</a
              >
            </template>
            <!-- 推局级 -->
            <!-- v-if="record.auditStatus == 'PAST' && record.pushOfficeId != 2" -->
            <template v-if="isShowBtn(record)">
              <a  @click="handleManage(3, record)"
                v-btnPermission="'tm_031_tjj_05'"
                >推局级</a
              >
            </template>
            <!-- 更多 -->
            <template
              v-if="record.status == 'REJECTED' && (postCode === 'BCLZGCS' || postCode === 'COTMBMJL' || postCode === 'COTMJSYWJL' || postCode === 'BCPMJSYWZB' || postCode === 'BCPMJSYWJL' || postCode === 'COTMJSYWZB')">
              <template style="color: #1890ff" v-if="record.auditStatus == 'DRAFT' || record.auditStatus == 'REJECTED'" class="mb12">
                <a @click="handleRemoveParams({ id: record.id, type: 1 })" v-btnPermission="'tm_031_del_03'">删除</a>
              </template>
              <template v-if="(record.source!='施组方案' && record.auditStatus !== 'DRAFT') || (record.source=='施组方案' && (record.pushOfficeAuditStatus && record.pushOfficeAuditStatus !== 'DRAFT'))">
                <approval-button :id="record.id" :status="record.auditStatus" v-btnPermission="'tm_031_loo_04'" />
              </template>
            </template>
            <template v-else>
              <template v-if="record.auditStatus == 'DRAFT' || record.auditStatus == 'REJECTED'">
                <a                  @click="handleRemoveParams({ id: record.id, type: 1 })"
                  v-btnPermission="'tm_031_del_03'"
                  >删除</a
                >
              </template>
              <!-- 审批 -->
              <template v-if="(record.source!='施组方案' && record.auditStatus !== 'DRAFT') || (record.source=='施组方案' && (record.pushOfficeAuditStatus && record.pushOfficeAuditStatus !== 'DRAFT'))">
                <approval-button  v-btnPermission="'tm_031_loo_04'"
                  :id="record.id"
                  :status="record.auditStatus"
                />
              </template>
            </template>
            <!-- 删除 -->
          </MoreButton>
          <!-- </MoreButton> -->
        </span>

        <span slot="auditStatusStr" slot-scope="text, record">
          <list-status :status="record.auditStatus" :isApproval="true" conversion="en" :text="text"></list-status>
        </span>
        <span slot="pushOfficeAuditStatusStr" slot-scope="text, record">
          <list-status :status="record.pushOfficeAuditStatus" :isApproval="true" conversion="en" :text="text"></list-status>
        </span>
      </list-table>
      <Version :visible="visible.versionVisible" @cancel="visible.versionVisible = false" :versionId="versionId"></Version>
    </a-card>
  </div>
</template>

<script>
import { STable } from '@/components'
import BasePage from '@/views/basePage' // 基础配置
import { getPlanHighlightsList, delPlanHighlights, getPlanHighlightsCount,findListDownListZip} from '@/api/technical/planHighlights'
import MoreButton from '@/components/MoreButton'
import OrgTreeSelect from '@/components/OrgTreeSelect'
import { planTypes, planClassic,statusData} from './model'
import { typeListApproval } from '@/utils/util'
import SelectProjectType from '@/components/Select/SelectProjectType' // 工程类别
import SelectTreeSubItem from '@/components/Select/SelectTreeSubItem' // 分部分项
import { listOption } from '@/api/technical/approvalPlan'
import Version from './version.vue'   //历史版本号
const columns = [
{
        title: '序号',
        width: '80px',
        scopedSlots: { customRender: 'serial' },
    },
  {
    title: '施组(方案名称)',
    dataIndex: 'nameStr',
    ellipsis: true,
    scopedSlots: { customRender: 'nameStr' }
  },
  {
    title: '方案类型',
    dataIndex: 'planTypeName',
    ellipsis: true
  },
  {
    title: '所属分公司',
    dataIndex: 'branchCompanyName',
    ellipsis: true
  },
  {
    title: '所属项目',
    dataIndex: 'projectName',
    ellipsis: true
  },
  {
    title: '版本号',
    dataIndex: 'versionNumber',
    scopedSlots: { customRender: 'versionNumber' }
  },
  {
    title: '来源',
    dataIndex: 'source',
  },
  {
    title: '填报人',
    dataIndex: 'creatorName'
  },
  {
    title: '填报时间',
    dataIndex: 'createTime'
  },
  {
    title: '状态',
    dataIndex: 'auditStatusStr',
    scopedSlots: { customRender: 'auditStatusStr' }
  },
  {
    title: '推局状态',
    dataIndex: 'pushOfficeAuditStatusStr',
    scopedSlots: { customRender: 'pushOfficeAuditStatusStr' }
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: '200px',
    scopedSlots: { customRender: 'operation' }
  }
]

export default {
  name: 'a' + Date.now(),
  extends: new BasePage(),
  components: {
    STable,
    MoreButton,
    Version,
  },
  data() {
    this.columns = columns

    return {
      // 统计
      statistics: {
        levelOfCompanyNum: 0,
        levelOfBureauNum: 0,
        companyRate: 0,
        bureauRate: 0
      },
      temp: () => {
        return (
          <span style="margin-right: 12px">
            公司级经典方案数量:{this.statistics.levelOfCompanyNum}&nbsp;&nbsp; 局级经典方案数量:
            {this.statistics.levelOfBureauNum}
            &nbsp;&nbsp; 公司级经典方案占比:{this.statistics.companyRate}%&nbsp;&nbsp; 局级经典方案占比:
            {this.statistics.bureauRate}%
          </span>
        )
      },
      selectedKeys: [],
      selectOptions: {},

      queryParam: {},
      postCode: this.$userInfo().currentPost.postCode,
      removeApi: { remove: delPlanHighlights }, // api
      visible: {
        versionVisible:false,
      },
      versionId:null,
      loadData: async (parameter) => {
        let requestParameters = Object.assign({}, parameter, { query: this.queryParam })
        this.getPlanHighlightsCountReq(requestParameters)
        return getPlanHighlightsList(requestParameters).then((res) => {
          res.data.forEach((i) => {
            i.nameStr = (i.classicsTypeName == '局优秀' ? '(局优秀)' : '(公司优秀)') + i.planName
          })
          console.log(res.data)
          return res
        })
      },
      downLoading:false,
      typeOption:[],
    }
  },
  mounted(){
    this.$refs.table.refresh(true)
    this.listOptionFn()
    
   },
   computed:{
    searchArr() {
      return [
      {
          name: '所属单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect
        },
        {
          name: '经典方案',
          value: 'classicsTypeId',
          type: 'select',
          data: planClassic
        },
        {
          name: '方案类型',
          value: 'planTypeId',
          type: 'select',
          data:  this.typeOption
        },
        {
          name: '方案名称',
          type: 'input',
          value: 'planName'
        },
        {
          name: '技术方案分类',
          type: 'input',
          value: 'technicalName'
        },
        {
          name: '工程类别',
          type: SelectProjectType,
          valueKey: 'projectQualityTypeId',
          showStop:false
        },
        {
          name: '分部分项',
          type: SelectTreeSubItem,
          valueKey: 'partId',
          keyValue: 'projectQualityTypeId',
          attrs: {
            fatherDisabled: true
          },
        },
        {
          name: '危大工程范围',
          type: 'input',
          value: 'dangerProjectTypeName'
        },
        {
          name: '新增状态',
          value: 'auditStatus',
          type: 'select',
          data: statusData
        },
        {
          name: '推局状态',
          value: 'pushOfficeAuditStatus',
          type: 'select',
          data: statusData
        },
      ]
    }
   },
  methods: {
      // 类别下拉
      listOptionFn() {
      listOption({ type: '5' }).then((res) => {
        this.typeOption = res.data;
        if(this.typeOption.length){
          this.typeOption.map((item)=>{
            item.label = item.name;
            item.value = item.id;
          })
        }
        this.searchTypeList = this.typeOption;
      })

    },
    isShowBtn(record){
      let flag = false;
      //record.auditStatus 新增状态不存在，推局状态 为不存在，待提交审核。不通过
      if(!record.auditStatus && (!record.pushOfficeAuditStatus || record.pushOfficeAuditStatus == 'DRAFT' || record.pushOfficeAuditStatus == 'REJECTED')){
        flag = true;
      //新增状态通过，推局状态 为不存在
      }else if(record.auditStatus == 'PAST' && (!record.pushOfficeAuditStatus || record.pushOfficeAuditStatus == 'DRAFT' ||  record.pushOfficeAuditStatus == 'REJECTED')){
        flag = true;
      }else{
        flag = false;
      }
      return flag;
    },
    getVersionNumber(text){
      let textName = text? 'V'+ text:'';
       return textName;
    },
     //点击查看版本号
    versionList(data){
     this.visible.versionVisible = true;
     this.versionId = data.programId;
    },
    getPlanHighlightsCountReq(requestParameters) {
      getPlanHighlightsCount(requestParameters).then((res) => {
        this.statistics = res.data
      })
    },
    //格式化当前日期
    formatDate(date, type = '-') {
      let M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      return date.getFullYear() + type + M + type + D
    },

    //搜索
    search(value) {
      value && (this.queryParam = value)
      if (!value.fillingInTimeBegin) {
        delete this.queryParam.fillingInTimeBegin
        delete this.queryParam.fillingInTimeEnd
      }
      this.$refs.table.refresh(true)
    },
    // 操作栏
    handleManage(type, record) {
      let query = {
        editModel: type == -1 ? 0 : type,
        tjj: type ==3
      }
      if (record && record.id) {
        query.id = record.id
      }
      this.$router.push({
        name: type == -1 ? 'planHighlightsTJJ' : 'updatePlanHighlights',
        query
      })
    },
        /**
     *@desc  下载
     *@param {}
     */
     async downZipFc(ids) {
      console.log('window.location', window.location)
      this.downLoading = true;
      let params = { ids, urlStr: window.location.origin }
      let res = await findListDownListZip(params)
      this.downLoading = false;
      this.handleDownload(res)
    },
    /**
     * 转义下载
     * @param parameter
     */
    handleDownload(res) {
      const blob = new Blob([res.data])
      const filename = decodeURIComponent(res.headers['content-disposition'].split('filename=')[1])
      console.log('filenamefilename', filename)
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = filename.substring(filename.indexOf("''") + 1) // 获取文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放blob对象
    },
  }
}
</script>
